package com.hrd.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hrd.common.util.ConstantUtil;
import com.hrd.common.util.Utils;
import com.hrd.common.util.bean.ServiceResult;
import com.hrd.common.util.date.DateUtils;
import com.hrd.common.util.date.EnumDateStyle;
import com.hrd.datasource.DatabaseContextHolder;
import com.hrd.mybatis.bean.auto.*;
import com.hrd.mybatis.bean.ext.ExtOrderModel;
import com.hrd.mybatis.mapper.auto.*;
import com.hrd.mybatis.mapper.ext.ExtArchivesMapper;
import com.hrd.service.CommonService;
import com.hrd.service.KingDeeService;
import com.hrd.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 刘江宁
 * @create 2022/1/12 17:58
 */
@Service
@Slf4j
public class OrderServiceImpl extends BaseServiceImpl implements OrderService {
    @Autowired
    TMLPlanBillMapper tmlPlanBillMapper;
    @Autowired
    PayTypeAccountRelateMapper payTypeAccountRelateMapper;
    @Autowired
    CommonService commonService;
    @Autowired
    KingDeeService kingDeeService;
    @Autowired
    TDCItemMapper tdcItemMapper;
    @Autowired
    HrdFailOrderMapper hrdFailOrderMapper;
    @Autowired
    TMLArchivesMapper tmlArchivesMapper;

    @Autowired
    TMLPlanBillEntryMapper tmlPlanBillEntryMapper;

    @Autowired
    HrdWarehouseRelationMapper hrdWarehouseRelationMapper;

    @Autowired
    TUserMapper tUserMapper;

    @Autowired
    HrdSynchLogMapper hrdSynchLogMapper;

    @Autowired
    TCurrencyMapper tCurrencyMapper;
    @Autowired
    TMachineMapper tMachineMapper;
    @Autowired
    TMLDayWorkBillMapper tmlDayWorkBillMapper;
    @Autowired
    ExtArchivesMapper extArchivesMapper;

    @Autowired
    HrdSpecialMapper hrdSpecialMapper;

    @Override
    public ServiceResult<String> syncCollectionOrder() {
        ServiceResult<String> result = new ServiceResult<>();

        //根据fThirdStatusID字段 判断是否需要同步
        //切换数据源到sqlserver
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        //查出需要同步的字段 为-0 需要同步 同步完成 设为1
        TMLPlanBillExample tmlPlanBillExample = new TMLPlanBillExample();
        tmlPlanBillExample.createCriteria()
                .andFthirdstatusidEqualTo(ConstantUtil.NEED_SYNC)
                .andFitemclassidEqualTo(ConstantUtil.COLLECTION_TYPE_ID_tMLPlanBill).andFstatusnameNotEqualTo("作废");
        tmlPlanBillExample.setOrderByClause("fPlanDate desc");


        List<TMLPlanBill> tmlPlanBills = tmlPlanBillMapper.selectByExample(tmlPlanBillExample);

        /*List<TMLPlanBill> tmlPlanBills = extArchivesMapper.selectListFk(new TMLPlanBill());*/
        if (tmlPlanBills.size() == 0) {
            result.setSuccess(false);
            result.setResult("没有可同步的数据");
            log.info("=======OrderServiceImple:syncCollectionOrder 没有可同步的数据========");
            return result;
        }


        //收款方式ID list
        List<Integer> fPayModeIdList0 = tmlPlanBills.stream().map(TMLPlanBill::getFpaymodeid).collect(Collectors.toList());
        List<Integer> fPayModeIdList = fPayModeIdList0.stream().distinct().collect(Collectors.toList());

        //收款方式名称list
        TDCItemExample tdcItemExample = new TDCItemExample();
        tdcItemExample.createCriteria()
                .andFidIn(fPayModeIdList);
        List<TDCItem> tdcItems = tdcItemMapper.selectByExample(tdcItemExample);

        List<String> fPayModeNameList = tdcItems.stream().map(TDCItem::getFname).collect(Collectors.toList());


        //根据收款方式 查出所有收款账户
        PayTypeAccountRelateExample payTypeAccountRelateExample = new PayTypeAccountRelateExample();
        //payTypeAccountRelateExample.createCriteria().andPaytypeIdIn(fPayModeNameList);

        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        List<PayTypeAccountRelate> payTypeAccountRelates = payTypeAccountRelateMapper.selectByExample(payTypeAccountRelateExample);
        result.setSuccess(true);
        result.setResult("同步成功");
        //构造金蝶接口参数
        String accessToken = commonService.getAccessToken().getResult();

        String url = "http://api.kingdee.com/jdy/arap/ar_credit_save?access_token=" + accessToken;

        //切换数据源到sqlserver
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        int i=0;
        for (TMLPlanBill t : tmlPlanBills) {
            log.info("共{}条，当前{}条",tmlPlanBills.size(),++i);
            DatabaseContextHolder.clearCustomerType();
            DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);

            List<TMLPlanBillEntry> entries = this.extArchivesMapper.selectListFk(t);
            if (CollectionUtil.isEmpty(entries)){
                TMLPlanBill newData = new TMLPlanBill();
                newData.setFid(t.getFid());
                newData.setFthirdstatusid(ConstantUtil.NO_NEED_SYNC);
                tmlPlanBillMapper.updateByPrimaryKeySelective(newData);
                continue;
            }


            try {
                JSONObject item = new JSONObject();

                String billdate = DateUtils.DateToString(t.getFplandate(), EnumDateStyle.YYYY_MM_DD);
                item.put("billno", t.getFno());
                item.put("remark", t.getFno());
                item.put("billdate", billdate);
                item.put("billsource", "pc");


                String payTypeName = tdcItems.stream().filter(o -> o.getFid().equals(t.getFpaymodeid())).findFirst().get().getFname();

                if (StringUtils.isNotBlank(payTypeName)){
                   if (payTypeName.indexOf("建行")!=-1 || payTypeName.indexOf("建设")!=-1){
                        payTypeName = "建设";
                    } else if (payTypeName.indexOf("交行")!=-1 || payTypeName.indexOf("交通")!=-1){
                        payTypeName = "交通";
                    }else{
                       payTypeName = "交通";
                   }
                }

                PayTypeAccountRelate payTypeAccountRelate = new PayTypeAccountRelate();

                for (PayTypeAccountRelate model : payTypeAccountRelates) {
                    if (model.getPaytypeName().contains(payTypeName)){
                        payTypeAccountRelate = model;
                    }

                }
                if (StringUtils.isBlank(payTypeAccountRelate.getSettleaccountId())){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("2");
                    hrdFailOrder.setFailMesaage(payTypeName+"没有对应收款账户");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }

                JSONObject payfromtoentry = new JSONObject();
                payfromtoentry.put("amount", t.getFtotalsum().toString());
                payfromtoentry.put("paytype_id", payTypeAccountRelate.getPaytypeId());
                //payfromtoentry.put("paytype_id", "3");

                payfromtoentry.put("settleaccount_id", payTypeAccountRelate.getSettleaccountId());
                //payfromtoentry.put("settleaccount_id", "1337707439956454400");




                //查出档案号
                //根据bill表主键找到 找到子表entry信息
                TMLPlanBillEntryExample tmlPlanBillEntryExample = new TMLPlanBillEntryExample();
                tmlPlanBillEntryExample.createCriteria()
                        .andFinteridEqualTo(t.getFid());
                List<TMLPlanBillEntry> tmlPlanBillEntries = tmlPlanBillEntryMapper.selectByExample(tmlPlanBillEntryExample);

                if (tmlPlanBillEntries.size() == 0) {
                    result.setSuccess(false);
                    result.setResult("存在同步失败的订单 没有找到档案号");
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("2");
                    hrdFailOrder.setFailMesaage("没有找到档案号");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    log.info("=======OrderServiceImple:syncCollectionOrder 存在同步失败的订单 没有找到档案号========");
                    continue;
                }

                TMLArchives tmlArchives = tmlArchivesMapper.selectByPrimaryKey(tmlPlanBillEntries.get(0).getFcitemid());
                if (tmlArchives==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("2");
                    hrdFailOrder.setFailMesaage("客户"+t.getFcitemid()+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }

                List<String> outOrderNoList = new ArrayList<>();
                for (TMLPlanBillEntry tmlPlanBillEntry : tmlPlanBillEntries) {
                    //档案号
                    TMLArchives outOrder = tmlArchivesMapper.selectByPrimaryKey(tmlPlanBillEntry.getFarchivesid());
                    if (outOrder.getFstatusid()==99){
                        continue;
                    }
                    outOrderNoList.add(outOrder.getFno());
                }

                String customerName = getCustomerName(outOrderNoList, tmlArchives.getFbackno().substring(tmlArchives.getFbackno().length() - 4) + tmlArchives.getFname());
                String kindDeeCustomerIdByName = kingDeeService.getKindDeeCustomerIdByName(customerName, accessToken);
                //String kindDeeCustomerIdByName = kingDeeService.getKindDeeCustomerIdByName("0537袁在龙-尹明超", headers, accessToken);

                if (StringUtils.isBlank(kindDeeCustomerIdByName)){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("金蝶客户"+tmlArchives.getFbackno().substring(tmlArchives.getFbackno().length() - 4) + tmlArchives.getFname()+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                item.put("itemclass_id",kindDeeCustomerIdByName );

                List<JSONObject> selbillinfoentryList = new ArrayList<>();

                //整机编号
                if (tmlPlanBillEntries==null && tmlPlanBillEntries.get(0)==null || tmlPlanBillEntries.get(0).getFmachineid()==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("2");
                    hrdFailOrder.setFailMesaage("整机编号不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                DatabaseContextHolder.clearCustomerType();
                DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
                TMLArchives tmlArchives1 = tmlArchivesMapper.selectByPrimaryKey(tmlPlanBillEntries.get(0).getFmachineid());
                if (tmlArchives1==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("2");
                    hrdFailOrder.setFailMesaage("整机编号不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                String customerField = tmlArchives1.getFname();


                String jbNO = "";

                List<JSONObject> otherBill = new ArrayList<>();
                HashMap<String,Double> cursettleamountMap = new HashMap<>();

                double count = 0;
                int reCount = 0;

                for (TMLPlanBillEntry tmlPlanBillEntry : tmlPlanBillEntries) {
                    JSONObject selbillinfoentry = new JSONObject();
                    selbillinfoentry.put("srcbilltypeid_id", ConstantUtil.BILL_TYPE_ID);
                    //档案号
                    TMLArchives outOrder = tmlArchivesMapper.selectByPrimaryKey(tmlPlanBillEntry.getFarchivesid());
                    if (outOrder.getFstatusid()==99){
                        continue;
                    }
                    String archives = outOrder.getFname();
                    String[] split = archives.split("\\|");
                    String newbillno = "";
                    if (split.length<3){
                        newbillno = archives;
                    }else{
                        newbillno = split[2]+"|"+split[0]+"|"+split[1];
                    }


                    //  使用档案号 调取金蝶 销售出库单接口 获取id 写入此处
                    JSONObject kingDeeOutbound = kingDeeService.getKingDeeOutbound(newbillno, accessToken);
                    if (kingDeeOutbound==null || kingDeeOutbound.get("id")==null){
                        continue;
                    }
                    String kingDeeOutboundId = kingDeeOutbound.get("id").toString();
                    Double totalunsettleamount = kingDeeOutbound.getDouble("totalunsettleamount");
                    if (cursettleamountMap.get(kingDeeOutboundId)!=null){
                        Double aDouble = cursettleamountMap.get(kingDeeOutboundId);
                        totalunsettleamount = totalunsettleamount+aDouble;
                    }

                    String cursettleamount = tmlPlanBillEntry.getFthistotal().toString();
                    if (totalunsettleamount.doubleValue()<Double.parseDouble(cursettleamount)){
                        cursettleamount = totalunsettleamount.toString();
                        JSONObject jsonData = new JSONObject();
                        jsonData.put("orderNo",t.getFno());
                        jsonData.put("billdate",billdate);
                        jsonData.put("biztype","1");
                        jsonData.put("itemclass_id",kindDeeCustomerIdByName);
                        List<JSONObject>  payfromtoentryList = new ArrayList<>();
                        JSONObject  payfromtoentryEntry = new JSONObject();
                        payfromtoentryEntry.put("paccttype_id","1295680181528197120");//工时费
                        payfromtoentryEntry.put("amount",(tmlPlanBillEntry.getFthistotal().doubleValue()-totalunsettleamount)+"");
                        payfromtoentryEntry.put("comment",t.getFno());
                        payfromtoentryList.add(payfromtoentryEntry);
                        jsonData.put("payfromtoentry",payfromtoentryList);
                        otherBill.add(jsonData);
                    }

                    selbillinfoentry.put("srcinterid", kingDeeOutboundId);
                    selbillinfoentry.put("cursettleamount",cursettleamount);

                    count = count +Double.parseDouble(cursettleamount);
                    if (cursettleamountMap.get(kingDeeOutboundId)==null){
                        cursettleamountMap.put("kingDeeOutboundId",Double.parseDouble(cursettleamount));
                    }else{
                        Double aDouble = cursettleamountMap.get(kingDeeOutboundId);
                        cursettleamountMap.put("kingDeeOutboundId",aDouble+Double.parseDouble(cursettleamount));
                    }

                    selbillinfoentryList.add(selbillinfoentry);
                    TMLArchives inOrder = tmlArchivesMapper.selectByPrimaryKey(outOrder.getFmachineid());
                    if (StringUtils.isBlank(jbNO)){
                        jbNO = inOrder.getFname();
                    }
                }

                if (count!=payfromtoentry.getDouble("amount")){
                    payfromtoentry.put("amount",String.valueOf(count));
                }

                if (tmlPlanBillEntries.size() != selbillinfoentryList.size()){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("2");
                    hrdFailOrder.setFailMesaage("出库单不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                payfromtoentry.put("custom_entity_field__4__1xooboid2d72_name", jbNO);



                List<JSONObject> payfromtoentryList = new ArrayList<>();
                payfromtoentryList.add(payfromtoentry);
                item.put("payfromtoentry", payfromtoentryList);

                item.put("selbillinfoentry", selbillinfoentryList);

                item.put("billsource", ConstantUtil.COLLECTION_BILL_SOURCE);

                // 整机编号 对应的 金蝶自定义字段 使用常量类中字段  测试账号没有自定义字段所以先注释
                item.put(ConstantUtil.CUSTOMER_FIELD, customerField);

                if (payfromtoentry.getDouble("amount")!=0) {
                    String kingDeeResult = kingDeeService.getKingDeeInterfacePost(item.toString(), url);
                    log.info("=======调用金蝶传递参数=> url:{}== param:{}========",url,item.toString());
                    log.info("=======金蝶返回数据:{}========",kingDeeResult);

                    JSONObject kingDeeResultObj = JSONObject.parseObject(kingDeeResult);
                    Boolean success = kingDeeResultObj.getBoolean("success");
                    if (!success) {
                        result.setSuccess(false);
                        result.setResult("存在同步失败的订单");
                        DatabaseContextHolder.clearCustomerType();
                        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                        HrdFailOrder hrdFailOrder = new HrdFailOrder();
                        hrdFailOrder.setOrderNo(t.getFno());
                        hrdFailOrder.setOrderType("2");
                        String msg = kingDeeResultObj.getString("msg");
                        if (StringUtils.isBlank(msg)){
                             msg = kingDeeResultObj.getString("message");
                        }
                        hrdFailOrder.setFailMesaage(msg);
                        hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                        hrdFailOrderMapper.insert(hrdFailOrder);
                        continue;
                    }
                    if (!kingDeeResultObj.getJSONObject("data").getBoolean("success")){
                        result.setSuccess(false);
                        result.setResult(kingDeeResultObj.getJSONObject("data").getJSONArray("errorInfo").getJSONObject(0).get("msg").toString());
                        log.info("=======OrderServiceImple:syncCollectionOrder {}========",result.getResult());
                        DatabaseContextHolder.clearCustomerType();
                        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                        HrdFailOrder hrdFailOrder = new HrdFailOrder();
                        hrdFailOrder.setOrderNo(t.getFno());
                        hrdFailOrder.setOrderType("2");
                        hrdFailOrder.setFailMesaage(result.getResult());
                        hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                        hrdFailOrderMapper.insert(hrdFailOrder);
                        continue;
                    }
                }
                //同步完成以后把thirdStatus字段设置为1

                TMLPlanBill newData = new TMLPlanBill();
                newData.setFid(t.getFid());
                newData.setFthirdstatusid(ConstantUtil.NO_NEED_SYNC);
                tmlPlanBillMapper.updateByPrimaryKeySelective(newData);
                //同步其他收款单
                if (CollectionUtil.isNotEmpty(otherBill)){
                //TODO
                    saveOtherBill(otherBill);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //写入日志
        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdSynchLog hrdSynchLog = new HrdSynchLog();
        hrdSynchLog.setSynchType(ConstantUtil.SYNC_TYPE_1);
        hrdSynchLog.setSynchTime(new Date().getTime()/1000+"");
        hrdSynchLogMapper.insert(hrdSynchLog);
        return result;
    }

    @Override
    public ServiceResult<String> syncSalesOutboundOrder() {


        // 查出hrd仓库关联信息

        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        List<HrdWarehouseRelation> hrdWarehouseRelations = hrdWarehouseRelationMapper.selectByExample(new HrdWarehouseRelationExample());



        ServiceResult<String> result = new ServiceResult<>();

        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        //查询需要修改的客户信息
        TMLArchivesExample tmlArchivesExample = new TMLArchivesExample();
        tmlArchivesExample.createCriteria()
                .andFthirdstatusidEqualTo(ConstantUtil.NEED_SYNC)
                .andFitemclassidEqualTo(ConstantUtil.OUTBOUND_TYPE_ID_tMLArchives)
                .andFcreatedateGreaterThanOrEqualTo(new Date(1667232000000L))
                .andFstatusnameNotEqualTo("作废");
        tmlArchivesExample.setOrderByClause("fDate DESC");
        List<TMLArchives> tmlArchives = tmlArchivesMapper.selectByExample(tmlArchivesExample);
        //List<TMLArchives> tmlArchives = this.extArchivesMapper.selectList(new TMLArchives());

        if (tmlArchives.size() == 0) {
            result.setSuccess(false);
            result.setResult("没有可同步的数据");
            log.info("=======OrderServiceImple:syncSalesOutboundOrder 没有可同步的数据========");
            return result;
        }
        result.setSuccess(true);
        result.setResult("同步成功");

        //构造金蝶接口参数
        String accessToken = commonService.getAccessToken().getResult();

        String url = "http://api.kingdee.com/jdy/sal/sal_outbound_save?access_token=" + accessToken;
        int i =0;
        for (TMLArchives t : tmlArchives) {

            log.info("共{}条，当前{}条",tmlArchives.size(),++i);
            DatabaseContextHolder.clearCustomerType();
            DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
            TMLArchives tmlArchives1 = this.tmlArchivesMapper.selectByPrimaryKey(t.getFid());
            if (tmlArchives1.getFthirdstatusid()==ConstantUtil.NO_NEED_SYNC){
                continue;
            }


            try {

                TMLArchives inOrder = tmlArchivesMapper.selectByPrimaryKey(t.getFmachineid());
                if (inOrder==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("旭冉商品信息"+t.getFmachineid()+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }

                JSONObject item = new JSONObject();
                item.put("billsource", ConstantUtil.OUTBOUND_BILL_SOURCE);
                String[] split = t.getFname().split("\\|");
                String newbillno = "";
                if (split.length<3){
                    newbillno = t.getFname();
                }else{
                    newbillno = split[2]+"|"+split[0]+"|"+split[1];
                }

                item.put("billno",newbillno);
                item.put("remark", t.getFno());
                String billdate = DateUtils.integerToString((int) (t.getFdate().getTime()/1000), EnumDateStyle.YYYY_MM_DD);
                item.put("billdate", billdate);
                //冉旭客户信息
                TMLArchives customer = tmlArchivesMapper.selectByPrimaryKey(t.getFcitemid());
                //调用金蝶客户接口查出主键id
                //item.put("customerid_id", kingDeeService.getKindDeeCustomerId(Utils.deleteStringChar(customer.getFno(),'_'), headers, accessToken));
                if (customer==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("客户"+t.getFcitemid()+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                }
                String kindDeeCustomerIdByName = kingDeeService.getKindDeeCustomerIdByName( customer.getFbackno().substring(customer.getFbackno().length() - 4)+customer.getFname() , accessToken);

                if (StringUtils.isBlank(kindDeeCustomerIdByName)){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("金蝶客户"+customer.getFbackno().substring(customer.getFbackno().length() - 4)+customer.getFname()+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }

                item.put("customerid_id", kindDeeCustomerIdByName);


                //冉旭职员信息
                TUser tUser = tUserMapper.selectByPrimaryKey(t.getFempid());
                List<Map> kindDeeEmpId = kingDeeService.getKindDeeEmpId(tUser.getFname(), accessToken);
                if (CollectionUtil.isEmpty(kindDeeEmpId)){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("职员"+tUser.getFname()+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                item.put("empid_id", kindDeeEmpId.get(0).get("id").toString());

                //获取规格名称
                if (t.getFmachinetypeid()==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("规格型号不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                //String machineType = tdcItemMapper.selectByPrimaryKey(t.getFmachinetypeid()).getFname();
                String machineType = tdcItemMapper.selectByPrimaryKey(inOrder.getFtypeid()).getFname();
                //通过规格名称 调用金蝶接口 模糊查询 获取 商品列表 查询完成后 筛选当前规格名称 并查询商品详情
                if (StringUtils.equals(machineType,"XE600DK MAX")){
                    machineType ="XE600D（MAX）";
                }
                JSONObject kindDeeMaterial = kingDeeService.getKindDeeMaterial(machineType, accessToken);
                if (kindDeeMaterial==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("商品："+machineType+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }



                List<JSONObject> material_entitys = new ArrayList<>();

                JSONObject material_entity = new JSONObject();
                material_entity.put("materialid_id", kindDeeMaterial.get("id"));
                material_entity.put("qty", "1");
                material_entity.put("unit_id", kindDeeMaterial.get("baseunitid_id"));
                material_entity.put("auxqty", "1");
                material_entity.put("auxunitid_id", kindDeeMaterial.get("baseunitid_id"));

                material_entity.put("price",t.getFselltotal() );
                material_entity.put("is_free", false);

                material_entity.put("kftype", kindDeeMaterial.get("kfperiodtype"));
                material_entity.put("kfperiod", "120");

                String kfdate = DateUtils.DateToString(inOrder.getFdateCc(), EnumDateStyle.YYYY_MM_DD);
                material_entity.put("kfdate",  kfdate);

                String validdate = DateUtils.integerToString((int) (inOrder.getFdateCc().getTime()/1000+(120*24*60*60)),EnumDateStyle.YYYY_MM_DD);
                material_entity.put("validdate", validdate);

               /* String kfdate = DateUtils.integerToString((int) (System.currentTimeMillis() / 1000), EnumDateStyle.YYYY_MM_DD);
                material_entity.put("kfdate",  "2022-01-01");

                String validdate = DateUtils.integerToString((int) (System.currentTimeMillis() / 1000+Long.parseLong((String) kindDeeMaterial.get("kfperiod")) *24*60), EnumDateStyle.YYYY_MM_DD);
                material_entity.put("validdate", "2027-01-01");*/

                material_entity.put("taxprice", t.getFselltotal());
                if (inOrder.getFstockid() != null && inOrder.getFstockid()!=0) {

                    List<HrdWarehouseRelation> collect = hrdWarehouseRelations.stream().filter(o -> inOrder.getFstockid().equals(o.getHrdWarehouseId())).collect(Collectors.toList());
                    if (CollectionUtil.isEmpty(collect)){
                        log.info("=======OrderServiceImple:syncBuyEntryOrder 仓库{}未关联========",inOrder.getFstockid());
                        DatabaseContextHolder.clearCustomerType();
                        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                        HrdFailOrder hrdFailOrder = new HrdFailOrder();
                        hrdFailOrder.setOrderNo(t.getFno());
                        hrdFailOrder.setOrderType("1");
                        hrdFailOrder.setFailMesaage("仓库"+t.getFstockid()+"未关联");
                        hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                        hrdFailOrderMapper.insert(hrdFailOrder);
                        continue;
                    }
                    HrdWarehouseRelation hrdWarehouseRelation = collect.get(0);
                    if (StringUtils.isNotBlank(hrdWarehouseRelation.getJdWarehouseId())) {
                        material_entity.put("stockid_id", hrdWarehouseRelation.getJdWarehouseId());
                    }else{
                        material_entity.put("stockid_id", "1487561151066683392");
                    }
                    if (StringUtils.isNotBlank(hrdWarehouseRelation.getJdSpaceId())) {
                        material_entity.put("spid_id", hrdWarehouseRelation.getJdSpaceId());
                    }
                }else{
                    material_entity.put("stockid_id", "1487561151066683392");
                    material_entity.put("stockid_number", "CK00029");

                    JSONObject job = getJdInOrderMaterialEntity(inOrder.getFno());
                    if (job!=null){
                        material_entity.put("spid_id", job.getString("spid_id"));
                        material_entity.put("stockid_id", job.getString("stockid_id"));
                        material_entity.put("stockid_number", job.getString("stockid_number"));
                    }
                }
                TDCItem tdcItem = this.tdcItemMapper.selectByPrimaryKey(t.getFsalemodeid());
                if (tdcItem==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage("工厂销售方式不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                JSONObject auxInfo = kingDeeService.getauxInfo(tdcItem.getFname(), accessToken);

                material_entity.put("custom_entity_field__4__1wn78y5plv07_id",auxInfo.getString("id"));
                //material_entity.put("spid_id", hrdWarehouseRelation.getJdSpaceId());
                material_entity.put("sn_list", inOrder.getFname());
                this.addAuxinfo(inOrder.getFname(), accessToken);
                material_entity.put("custom_entity_field__4__1xooboid2d72_name", inOrder.getFname());
                material_entity.put("fzhongjiefei", t.getFnum2());
                material_entity.put(ConstantUtil.CUSTOMER_FIELD2, t.getFisold());
                TCurrencyExample tCurrencyExample = new TCurrencyExample();
                tCurrencyExample.createCriteria()
                        .andFidEqualTo(t.getFarchivesid());

                //查出旧机信息从表
                TMLDayWorkBillExample tmlDayWorkBillExample = new TMLDayWorkBillExample();
                tmlDayWorkBillExample.createCriteria()
                        .andFarchivesidEqualTo(t.getFid());
                List<TMLDayWorkBill> tmlDayWorkBills = tmlDayWorkBillMapper.selectByExample(tmlDayWorkBillExample);
               /* if (tmlDayWorkBills.size() == 0) {
                    result.setSuccess(false);
                    result.setResult("存在同步失败的订单 没有找到旧机信息");
                    log.info("=======OrderServiceImple:syncSalesOutboundOrder 存在同步失败的订单 没有找到旧机信息========");
                    continue;
                }*/
                //旧机信息


                material_entity.put("jiuchejixing", t.getFoldbrand());
                if (tmlDayWorkBills.size() != 0) {
                    TMLDayWorkBill tmlDayWorkBill = tmlDayWorkBills.get(0);
                    material_entity.put("fjiujipinggujia", tmlDayWorkBill.getFmoney5());

                    material_entity.put("jiujihuishoujia",tmlDayWorkBill.getFoldprice());
                    material_entity.put("fchajia", tmlDayWorkBill.getFoldprice().subtract(tmlDayWorkBill.getFmoney5()).toString());
                }
                material_entity.put("fpeijianzengsong", t.getFtotal9());
                material_entitys.add(material_entity);
                item.put("material_entity", material_entitys);
                item.put("remark", t.getFno());
                String kingDeeResult = kingDeeService.getKingDeeInterfacePost(item.toString(), url);

                log.info("=======调用金蝶传递参数=> url:{}== param:{}========",url,item.toString());
                log.info("**********************=======金蝶返回数据:{}========",kingDeeResult);

                JSONObject kingDeeResultObj = JSONObject.parseObject(kingDeeResult);
                Boolean success = kingDeeResultObj.getBoolean("success");
                if (!success) {
                    result.setSuccess(false);
                    result.setResult("存在同步失败的数据");
                    log.info("=======OrderServiceImple:syncSalesOutboundOrder 存在同步失败的数据========");
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    hrdFailOrder.setFailMesaage(kingDeeResultObj.getString("message"));
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                if (!kingDeeResultObj.getJSONObject("data").getBoolean("success")){
                    result.setSuccess(false);

                    log.info("=======OrderServiceImple:syncCollectionOrder {}========",result.getResult());
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("1");
                    JSONObject data = kingDeeResultObj.getJSONObject("data");
                    hrdFailOrder.setFailMesaage(data.getString("message"));
                    if (data.get("errorInfo")!=null){
                        JSONArray errorInfo = data.getJSONArray("errorInfo");
                        if (errorInfo.size()!=0){
                            JSONObject o = (JSONObject) errorInfo.get(0);
                            hrdFailOrder.setFailMesaage(o.getString("msg"));
                        }
                    }
                    result.setResult(hrdFailOrder.getFailMesaage());
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    result.setResult(hrdFailOrder.getFailMesaage());
                    continue;
                }
                //同步完成以后把thirdStatus字段设置为1

                TMLArchives newData = new TMLArchives();
                newData.setFid(t.getFid());
                newData.setFthirdstatusid(ConstantUtil.NO_NEED_SYNC);
                tmlArchivesMapper.updateByPrimaryKeySelective(newData);
                log.info("================同步结束====================");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //写入日志
        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdSynchLog hrdSynchLog = new HrdSynchLog();
        hrdSynchLog.setSynchType(ConstantUtil.SYNC_TYPE_2);
        hrdSynchLog.setSynchTime(new Date().getTime()/1000+"");
        hrdSynchLogMapper.insert(hrdSynchLog);
        return result;
    }

    @Override
    public ServiceResult<String> syncBuyEntryOrder() {


        // 查出hrd仓库关联信息

        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        List<HrdWarehouseRelation> hrdWarehouseRelations = hrdWarehouseRelationMapper.selectByExample(new HrdWarehouseRelationExample());



        ServiceResult<String> result = new ServiceResult<>();

        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        //查询需要修改的客户信息
        TMLArchivesExample tmlArchivesExample = new TMLArchivesExample();
        tmlArchivesExample.createCriteria()
                .andFthirdstatusidEqualTo(ConstantUtil.NEED_SYNC)
                .andFitemclassidEqualTo(ConstantUtil.ENTRY_TYPE_ID_tMLArchives).andFstatusidNotEqualTo(99);
        List<TMLArchives> tmlArchives = tmlArchivesMapper.selectByExample(tmlArchivesExample);

        if (tmlArchives.size() == 0) {
            result.setSuccess(false);
            result.setResult("没有可同步的数据");
            log.info("=======OrderServiceImple:syncBuyEntryOrder 入库单同步没有可同步的数据========");
            return result;
        }
        result.setSuccess(true);
        result.setResult("同步成功");

        //构造金蝶接口参数
        String accessToken = commonService.getAccessToken().getResult();

        String url = "http://api.kingdee.com/jdy/pur/pur_inbound_save?access_token=" + accessToken;
        int i = 0;
        for (TMLArchives t : tmlArchives) {
            log.info("共{}条，当前{}条",tmlArchives.size(),++i);
            DatabaseContextHolder.clearCustomerType();
            DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
            TMLArchives tmlArchives1 = this.tmlArchivesMapper.selectByPrimaryKey(t.getFid());
            if (tmlArchives1.getFthirdstatusid()==ConstantUtil.NO_NEED_SYNC){
                continue;
            }

            TMachineExample tMachineExample = new TMachineExample();
            TMachineExample.Criteria criteria = tMachineExample.createCriteria();
            criteria.andFinteridEqualTo(t.getFid());
            List<TMachine> tMachines = tMachineMapper.selectByExample(tMachineExample);

            try {
                //查询入库单
                //获取字表信息

                String billdate = DateUtils.DateToString(tMachines.get(0).getFplandate(), EnumDateStyle.YYYY_MM_DD);

                JSONObject item = new JSONObject();
                item.put("transtype", "2");

                item.put("billno", t.getFname());
                item.put("remark", t.getFno());
                item.put("billdate", billdate);
                item.put("supplierid_id", "1244960715270285312");
                item.put("supplierid_number", "01WZ.0001XGWJ");
               /* item.put("supplierid_id", "1296402188104385536");
                item.put("supplierid_number", "GYS00003");*/


                //获取规格名称
                String machineType = tdcItemMapper.selectByPrimaryKey(t.getFtypeid()).getFname();
                if (StringUtils.equals(machineType,"XE600DK MAX")){
                    machineType ="XE600D（MAX）";
                }
                //通过规格名称 调用金蝶接口 模糊查询 获取 商品列表 查询完成后 筛选当前规格名称 并查询商品详情
                JSONObject kindDeeMaterial = kingDeeService.getKindDeeMaterial(machineType, accessToken);
                if (kindDeeMaterial==null){
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("0");
                    hrdFailOrder.setFailMesaage("商品："+machineType+"不存在");
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                JSONArray priceentity = kindDeeMaterial.getJSONArray("priceentity");



                List<JSONObject> material_entitys = new ArrayList<>();

                JSONObject material_entity = new JSONObject();
                if (t.getFselltotal()!=null && t.getFselltotal().doubleValue()!=0) {
                    material_entity.put("taxprice",t.getFselltotal());
                }else{
                    material_entity.put("taxprice",new BigDecimal(1));
                }
                material_entity.put("materialid_id", kindDeeMaterial.get("id"));
                material_entity.put("materialid_number", kindDeeMaterial.get("number"));
                material_entity.put("unit_id", kindDeeMaterial.get("baseunitid_id"));
                material_entity.put("qty", "1");
                //material_entity.put("taxprice", t.getFselltotal());
                material_entity.put("kftype", kindDeeMaterial.get("kfperiodtype"));
                material_entity.put("kfperiod", "120");

                String kfdate = DateUtils.DateToString(t.getFdateCc(), EnumDateStyle.YYYY_MM_DD);
                material_entity.put("kfdate",  kfdate);

                String validdate = DateUtils.integerToString((int) (t.getFdateCc().getTime()/1000+(120*24*60*60)),EnumDateStyle.YYYY_MM_DD);
                material_entity.put("validdate", validdate);


                /*material_entity.put("kfdate",  "2022-01-01");

                material_entity.put("validdate", "2027-01-01");*/

                material_entity.put("sn_list", t.getFno());
                this.addAuxinfo(t.getFno(), accessToken);
                material_entity.put("custom_entity_field__4__1xooboid2d72_name", t.getFno());



                if (t.getFstockid() != null && t.getFstockid()!=0) {
                    List<HrdWarehouseRelation> collect = hrdWarehouseRelations.stream().filter(o -> t.getFstockid().equals(o.getHrdWarehouseId())).collect(Collectors.toList());
                    if (CollectionUtil.isEmpty(collect)){
                        log.info("=======OrderServiceImple:syncBuyEntryOrder 仓库{}未关联========",t.getFstockid());
                        DatabaseContextHolder.clearCustomerType();
                        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                        HrdFailOrder hrdFailOrder = new HrdFailOrder();
                        hrdFailOrder.setOrderNo(t.getFno());
                        hrdFailOrder.setOrderType("0");
                        hrdFailOrder.setFailMesaage("仓库"+t.getFstockid()+"未关联");
                        hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                        hrdFailOrderMapper.insert(hrdFailOrder);
                        continue;
                    }
                    HrdWarehouseRelation hrdWarehouseRelation = collect.get(0);


                    if (StringUtils.isNotBlank(hrdWarehouseRelation.getJdWarehouseId()) ) {
                        material_entity.put("stockid_id", hrdWarehouseRelation.getJdWarehouseId());
                    }else{
                        log.info("=======OrderServiceImple:syncBuyEntryOrder 仓库{}未关联========",t.getFstockid());
                        DatabaseContextHolder.clearCustomerType();
                        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                        HrdFailOrder hrdFailOrder = new HrdFailOrder();
                        hrdFailOrder.setOrderNo(t.getFno());
                        hrdFailOrder.setOrderType("0");
                        hrdFailOrder.setFailMesaage("仓库"+t.getFstockid()+"未关联");
                        hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                        hrdFailOrderMapper.insert(hrdFailOrder);
                        continue;
                    }
                    if (StringUtils.isNotBlank(hrdWarehouseRelation.getJdWarehouseNumber())) {
                        material_entity.put("stockid_number", hrdWarehouseRelation.getJdWarehouseNumber());
                    }else{
                        log.info("=======OrderServiceImple:syncBuyEntryOrder 仓库{}未关联========",t.getFstockid());
                        DatabaseContextHolder.clearCustomerType();
                        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                        HrdFailOrder hrdFailOrder = new HrdFailOrder();
                        hrdFailOrder.setOrderNo(t.getFno());
                        hrdFailOrder.setOrderType("0");
                        hrdFailOrder.setFailMesaage("仓库"+t.getFstockid()+"未关联");
                        hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                        hrdFailOrderMapper.insert(hrdFailOrder);
                        continue;
                    }
                    if (StringUtils.isNotBlank(hrdWarehouseRelation.getJdSpaceId())) {
                        material_entity.put("spid_id", hrdWarehouseRelation.getJdSpaceId());
                    }
                }else{
                    material_entity.put("stockid_id", "1487561151066683392");
                    material_entity.put("stockid_number", "CK00029");
                }


                material_entitys.add(material_entity);
                item.put("material_entity", material_entitys);

                /*JSONObject item0 = new JSONObject();
                item0.put("number",t.getFno());
                String url0 = "http://api.kingdee.com/jdy/pur/pur_inbound_detail?access_token=" + accessToken;
                String kingDeeResult0 = kingDeeService.getKingDeeInterfacePost(item0.toString(), url0, headers);
                JSONObject kingDeeResultObj0 = JSONObject.parseObject(kingDeeResult0);
                if (kingDeeResultObj0!=null && kingDeeResultObj0.get("data")!=null){
                    JSONObject data = kingDeeResultObj0.getJSONObject("data");
                    if (data.get("id")!=null){
                        item.put("id",data.getString("id"));
                    }
                }*/


                String kingDeeResult = kingDeeService.getKingDeeInterfacePost(item.toString(), url);
                log.info("=======调用金蝶传递参数=> url:{}== param:{}========",url,item.toString());
                log.info("=======金蝶返回数据:{}========",kingDeeResult);

                JSONObject kingDeeResultObj = JSONObject.parseObject(kingDeeResult);
                Boolean success = kingDeeResultObj.getBoolean("success");
                if (!success) {
                    result.setSuccess(false);
                    log.info("=======OrderServiceImple:syncBuyEntryOrder 存在同步失败的数据========");
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("0");
                    hrdFailOrder.setFailMesaage(kingDeeResultObj.getString("message"));
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                if (!kingDeeResultObj.getJSONObject("data").getBoolean("success")){
                    result.setSuccess(false);
                    result.setResult(kingDeeResultObj.getJSONObject("data").getJSONArray("errorInfo").getJSONObject(0).get("msg").toString());
                    log.info("=======OrderServiceImple:syncCollectionOrder {}========",result.getResult());
                    DatabaseContextHolder.clearCustomerType();
                    DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                    HrdFailOrder hrdFailOrder = new HrdFailOrder();
                    hrdFailOrder.setOrderNo(t.getFno());
                    hrdFailOrder.setOrderType("0");
                    hrdFailOrder.setFailMesaage(kingDeeResultObj.getString("message")==null?result.getResult():kingDeeResultObj.getString("message"));
                    hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                    hrdFailOrderMapper.insert(hrdFailOrder);
                    continue;
                }
                //同步完成以后把thirdStatus字段设置为1

                TMLArchives newData = new TMLArchives();
                newData.setFid(t.getFid());
                newData.setFthirdstatusid(ConstantUtil.NO_NEED_SYNC);
                tmlArchivesMapper.updateByPrimaryKeySelective(newData);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        //写入日志
        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdSynchLog hrdSynchLog = new HrdSynchLog();
        hrdSynchLog.setSynchType(ConstantUtil.SYNC_TYPE_3);
        hrdSynchLog.setSynchTime(new Date().getTime()/1000+"");
        hrdSynchLogMapper.insert(hrdSynchLog);
        return result;
    }

    /**
     * 新增辅助资料
     * @return
     */
    public JSONObject addAuxinfo(String number, String token){
        //查询辅助资料
        JSONObject kingAuxinfo = this.kingDeeService.getKingAuxinfo(number, token);
        if (kingAuxinfo==null || kingAuxinfo.get("id")==null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("number", number);
            jsonObject.put("name", number);
            jsonObject.put("group_id", "1216476591786301440");


            String url = "http://api.kingdee.com/jdy/basedata/auxinfo_save?access_token=" + token;
            String kingDeeResult = kingDeeService.getKingDeeInterfacePost(jsonObject.toString(), url);
            log.info("=======调用金蝶传递参数=> url:{}== param:{}========",url,jsonObject.toString());
            log.info("=======金蝶返回数据:{}========",kingDeeResult);

            JSONObject kingDeeResultObj = JSONObject.parseObject(kingDeeResult);
        }
        return kingAuxinfo;
    }

    @Override
    public ServiceResult<List<ExtOrderModel>> list(ExtOrderModel form) {
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        ServiceResult<List<ExtOrderModel>> result = new ServiceResult<>();
        List<ExtOrderModel> orderList = this.extOrderMapper.selectList(form);
        result.setSuccess(true);
        result.setResult(orderList);
        return result;
    }

    @Override
    public Integer count(ExtOrderModel form) {
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        return this.extOrderMapper.selectCount(form);
    }

    @Override
    public ServiceResult<ExtOrderModel> synchOrder(ExtOrderModel form) {
        ServiceResult<ExtOrderModel> result = new ServiceResult<>();
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        if (StringUtils.equals(form.getOrderType(), "收款单")) {
            TMLPlanBill tmlPlanBill = new TMLPlanBill();
            tmlPlanBill.setFid(Integer.parseInt(form.getOrderId()));
            tmlPlanBill.setFthirdstatusid(0);
            this.tmlPlanBillMapper.updateByPrimaryKeySelective(tmlPlanBill);
        }else{
            TMLArchives tmlArchives = new TMLArchives();
            tmlArchives.setFid(Integer.parseInt(form.getOrderId()));
            tmlArchives.setFthirdstatusid(0);
            this.tmlArchivesMapper.updateByPrimaryKeySelective(tmlArchives);
        }
        result.setResult(form);
        result.setSuccess(true);
        return result;
    }

    @Override
    public ServiceResult<ExtOrderModel> fkOrderSynchAction(ExtOrderModel form) {
        ServiceResult<ExtOrderModel> result = new ServiceResult<>();
        this.syncCollectionOrder();
        result.setSuccess(true);
        return result;
    }

    @Override
    public ServiceResult<ExtOrderModel> ckOrderSynchAction(ExtOrderModel form) {
        ServiceResult<ExtOrderModel> result = new ServiceResult<>();
        this.syncSalesOutboundOrder();
        result.setSuccess(true);
        return result;
    }

    @Override
    public ServiceResult<ExtOrderModel> rkOrderSynchAction(ExtOrderModel form) {
        ServiceResult<ExtOrderModel> result = new ServiceResult<>();
        this.syncBuyEntryOrder();
        result.setSuccess(true);
        return result;
    }

    @Override
    public ServiceResult<ExtOrderModel> allOrderSynchAction(ExtOrderModel form) {
        ServiceResult<ExtOrderModel> result = new ServiceResult<>();
        this.syncBuyEntryOrder();
        this.syncSalesOutboundOrder();
        this.syncCollectionOrder();
        result.setSuccess(true);
        return result;
    }

    public JSONObject getJdInOrderMaterialEntity(String orderNo){

        String accessToken = commonService.getAccessToken().getResult();


        JSONObject item0 = new JSONObject();
        item0.put("number", orderNo);
        String url0 = "http://api.kingdee.com/jdy/pur/pur_inbound_detail?access_token=" + accessToken;
        String kingDeeResult0 = kingDeeService.getKingDeeInterfacePost(item0.toString(), url0);
        JSONObject kingDeeResultObj0 = JSONObject.parseObject(kingDeeResult0);
        if (kingDeeResultObj0 != null && kingDeeResultObj0.get("data") != null) {
            JSONObject data = kingDeeResultObj0.getJSONObject("data");
            if (data.get("material_entity")!=null) {
                JSONArray materialEntity = data.getJSONArray("material_entity");
                if (materialEntity!= null && materialEntity.size()!=0) {
                    JSONObject job = (JSONObject) materialEntity.get(0);
                    return job;
                }
            }
        }
        return null;
    }

    public JSONObject getOutBill(String orderNo){

        String accessToken = commonService.getAccessToken().getResult();


        JSONObject item0 = new JSONObject();
        item0.put("number", orderNo);
        String url0 = "http://api.kingdee.com/jdy/pur/sal_outbound_detail?access_token=" + accessToken;
        String kingDeeResult0 = kingDeeService.getKingDeeInterfacePost(item0.toString(), url0);
        JSONObject kingDeeResultObj0 = JSONObject.parseObject(kingDeeResult0);
        if (kingDeeResultObj0 != null && kingDeeResultObj0.get("data") != null) {
            JSONObject data = kingDeeResultObj0.getJSONObject("data");
            return data;
        }
        return null;
    }

    /**
     * 同步娶她收款单
     */
    private void saveOtherBill(List<JSONObject> params){

        String accessToken = commonService.getAccessToken().getResult();

        String url = "http://api.kingdee.com/jdy/arap/ar_other_credit_save?access_token="+accessToken;
        for (JSONObject param : params) {
            param.put("billsource", "pc");
            String kingDeeResult = kingDeeService.getKingDeeInterfacePost(param.toString(), url);
            log.info("=======调用金蝶传递参数=> url:{}== param:{}========",url,param.toString());
            log.info("=======金蝶返回数据:{}========",kingDeeResult);

            JSONObject kingDeeResultObj = JSONObject.parseObject(kingDeeResult);
            Boolean success = kingDeeResultObj.getBoolean("success");
            if (!success) {
                log.info("=======OrderServiceImple:syncBuyEntryOrder 存在同步失败的数据========");
                DatabaseContextHolder.clearCustomerType();
                DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
                HrdFailOrder hrdFailOrder = new HrdFailOrder();
                hrdFailOrder.setOrderNo(param.getString("orderNo"));
                hrdFailOrder.setOrderType("0");
                hrdFailOrder.setFailMesaage(param.getString("orderNo")+"其他收款单同步失败");
                hrdFailOrder.setCreateTime(DateUtils.getNowServerDate());
                hrdFailOrderMapper.insert(hrdFailOrder);
                continue;
            }
        }

    }
    public String getCustomerName(List<String> orderList,String cusromer){
        if (CollectionUtil.isEmpty(orderList)){
            return cusromer;
        }
        if (StringUtils.isBlank(cusromer)){
            return cusromer;
        }
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdSpecialExample example = new HrdSpecialExample();
        HrdSpecialExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNoIn(orderList);
        criteria.andSourceCustomerEqualTo(cusromer);
        List<HrdSpecial> hrdSpecials = this.hrdSpecialMapper.selectByExample(example);
        if (CollectionUtil.isEmpty(hrdSpecials)){
            return cusromer;
        }else{
            return hrdSpecials.get(0).getTargetCustomer();
        }

    }
}
